<template>
  <div class="container">
    <router-view></router-view>
  </div>
</template>

<script >
import $api from "@/api/index"
import configEnv from '_conf'

export default {
  name: "App",
  components: {},
  data(){
    return{
      code:'',
      is:''
    }
  },
  watch:{
    $route:{
      handler(val,oldval){
        if(val.name!=='selectTryCourse'){
          if (!window.localStorage.getItem('openId')) { // 如果缓存localStorage中没有微信openId，则需用code去后台获取
             this.getCode()
          }
        }
      }
    }
  },
  methods: {
    // 获取code
    getCode () { // 非静默授权，第一次有弹框
      this.code = ''
      let local = window.location.href// 获取页面url
      let appid = configEnv.appId
      this.code = this.getUrlCode().code // 截取code
      if (this.code == null || this.code === '') { // 如果没有code，则去请求
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
      } else {
        // 你自己的业务逻辑
        this.getOpenId()
      }
    },
    getUrlCode() { // 截取url中的code方法
      var url = location.search
      this.winUrl = url
      var theRequest = new Object()
      if (url.indexOf("?") != -1) {
        var str = url.substr(1)
        var strs = str.split("&")
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1])
        }
      }
      return theRequest
    },
    // 获取微信openid 以及登录状态
    async getOpenId(){
      const res = await $api.user.getOpenId({code: this.code})
      let data = res.data
      localStorage.setItem('openId', data.openid)
      localStorage.setItem('WxInfo', JSON.stringify(data))
      this.blockLoading = false
    },
  }
};
</script>

<style lang="scss">
html,
body {
  height: 100%;
  width: 100%;
}
</style>
